import * as commonTrackInfo from 'src/common/trackConfigs';

const trackEventIDs = {
  ...commonTrackInfo
};

/**
 * 获取当前页面的pageID并进行设置
 * @param {*} to
 * @returns {void}
 */
export function setCurrentPageId(to) {
  const { pageID: tPageID, title: tTitle, pageName: tPageName = '' } = to.meta;
  window.MTrackJson = {};
  if (!tPageID) {
    window.MTrackJson['WT.pageID'] = '';
    window.MTrackJson['WT.pagename'] = '';
    window.oPageID = '';
    window.oPagename = '';
    return '';
  }
  const WTpageName =
    tPageName || tTitle || window.MTrackJson['WT.pagename'] || '微应用B';
  window.MTrackJson['WT.pageID'] = tPageID;
  window.MTrackJson['WT.pagename'] = WTpageName;
  window.oPageID = '';
  window.oPagename = '';
}

/**
 * 获取当前页面的埋点信息区分菜单页面信息
 * @param {*} banksdcOpts 埋点信息
 * @returns {{pageID: {String}, pageName: {String}}}
 */
export function getCurrentPageInfo(banksdcOpts = {}) {
  const { isMenu = false, menuPageID, menuPagetitle } = banksdcOpts;
  const pageID =
    window.oPageID || (window.MTrackJson ? window.MTrackJson['WT.pageID'] : '');
  const pageName =
    window.oPagename ||
    (window.MTrackJson ? window.MTrackJson['WT.pagename'] : '');
  return {
    pageID: isMenu ? menuPageID : pageID,
    pageName: isMenu ? menuPagetitle : pageName
  };
}

/**
 * 埋点事件处理
 * @param {*} e 事件对象
 * @param {*} autoTrack 是否需要点击自动上报（逐步移除， 一期需求使用）
 * @param {*} eventType 事件类型 hover | click | default
 * @returns
 */
export function trackHandler(e, autoTrack, eventType) {
  const dateset = getTrackBaseInfo(e); // 获取埋点的基础信息
  const {
    tiid = '',
    olabelid = '',
    configPageId = '',
    configPageName = ''
  } = dateset;
  let sdcParams = {};

  sdcParams = getTrackPageInfo({
    configPageId,
    olabelid,
    tiid,
    handTrack: true
  });

  if (!sdcParams) return;
  const configTrackInfo = {}; // 获取自定义埋点信息
  const pageInfo = {
    'wt-pageID':
      configPageId || window.oPageID || window.MTrackJson['WT.pageID'],
    'wt-pagename':
      configPageName || window.oPagename || window.MTrackJson['WT.pagename']
  };
  const {
    olabel,
    otitle: ti,
    'wt-olabelid': wtOlabelid,
    'wt-pageId': pageID,
    'wt-pagename': pageName,
    'wt-tiid': wtTiid
  } = {
    ...configTrackInfo,
    ...pageInfo,
    ...sdcParams
  };
  window.trackHandler(
    {
      configPageId: pageID,
      configPageName: pageName,
      trackBefore: (info = {}) => {
        info['wt-olabel'] = olabel;
        info['wt-olabelid'] = wtOlabelid;
        info['wt-ti'] = ti;
        info['wt-tiid'] = wtTiid;
        return info;
      }
    },
    autoTrack,
    eventType
  );
}

function getTrackBaseInfo(info = {}) {
  const { dateset = {} } = info.target || {};
  return info.target ? dateset : info;
}

/**
 * 获取页面区域和内容信息
 * @param {*} trackDatas 埋点配置的数据信息
 * @returns
 */
function getTrackPageInfo(trackDatas) {
  const {
    configPageid,
    olabelid: areaID,
    tiid: contentID,
    handTrack = false
  } = trackDatas;
  const { pageID } = getCurrentPageInfo(); // 当前页面信息
  const parsePageID = (configPageid || pageID || '').replace(/-/g, '');
  const pageSdcInfo = trackEventIDs[parsePageID] || {};
  let trackInfo = {};
  if (!areaID || !pageID) return trackInfo;
  const publicAreaSdcInfo = trackEventIDs[areaID];
  const pageAreaSdcInfo = pageSdcInfo[`${parsePageID}-${areaID}`];
  let areaTrackInfo = pageAreaSdcInfo;
  if (!contentID) {
    trackInfo = publicAreaSdcInfo ? publicAreaSdcInfo[areaID] : pageAreaSdcInfo;
  } else {
    const currentTrackInfo = publicAreaSdcInfo || pageSdcInfo;
    if (publicAreaSdcInfo) {
      areaTrackInfo = publicAreaSdcInfo[areaID];
    }
    trackInfo = currentTrackInfo[`${areaID}-${contentID}`] || {};
    // 手动埋点的数据
    if (handTrack) {
      return {
        ...trackInfo,
        ...areaTrackInfo
      };
    }
  }
  return {
    ...trackInfo,
    ...areaTrackInfo
  };
}

/**
 * 设置元素的data
 * @param {*} areaID
 * @param {*} contentID
 * @returns
 */
function setDataOnEle(areaID, contentID) {
  const datas = getTrackPageInfo({
    olabelid: areaID,
    tiid: contentID
  });
  const datasObj = {};
  Object.keys(datas).forEach(item => {
    const restItem = item.includes('wt-') ? item.replace('wt-', '') : item;
    datasObj[`data-${restItem}`] = datas[item];
  });
  return datasObj;
}

/**
 * 循环埋点上报
 * @param {*} lst
 * @param {*} injectVal
 * @returns
 */
function repeatPostTrackInfo(lst = [], injectVal = {}) {
  if (!lst.length) return;
  lst.forEach(item => {
    async () => {
      await trackHandler({
        ...item,
        ...injectVal
      });
    };
  });
}

/**
 * 插件安装注册方法
 * @param {*} Vue
 * @param {*} opts
 * @returns
 */
const install = (Vue, opts = {}) => {
  if (install.installed) return;
  install.installed = true;
  install.opts = opts; // 注册时配置
  Object.defineProperties(Vue.prototype, {
    $trackHandler: {
      get() {
        return trackHandler;
      }
    },
    $getTrackInfo: {
      get() {
        return setDataOnEle;
      }
    },
    $getAutoTrackInfo: {
      get() {
        return getTrackPageInfo;
      }
    },
    $repeatPostTrackInfo: {
      get() {
        return repeatPostTrackInfo;
      }
    }
  });
};

export default {
  install
};
